# # -*- coding: utf-8 -*-

import json
import os
import shutil

import jinja2
import jsonpath

import jMeterUtil
from jsonUtil import set_val

JMETER_Home = r'''"D:\Program Files\apache-jmeter-5.5\bin\jmeter.bat"'''


def run(tpl_name='凭证推送报文', num_threads=2, count=1):
    test_name = tpl_name
    jmx_path = f'jmx/tpl/{test_name}.jmx'
    jmx_file = f'run/{test_name}.jmx'

    report_dir = os.path.realpath(f'report/{test_name}')
    report_html_dir = os.path.join(report_dir, f'html_{count}_{num_threads}')
    result_file = os.path.join(report_dir, f'{test_name}_{count}_{num_threads}.csv')

    if os.path.exists(report_html_dir):
        shutil.rmtree(report_html_dir)

    if os.path.exists(result_file):
        os.remove(result_file)

    if not os.path.exists(report_html_dir):
        os.makedirs(report_html_dir)

    params = {
        "http": {
            "domain": "10.2.36.187",
            "port": 9709,
            "protocol": "http",
            "post_argument_value": "{}"
        },
        "thread": {
            "num_threads": num_threads,
        }
    }

    tpl_data_path = "jmx/data/{}.json".format(test_name)

    with open(tpl_data_path, encoding='utf-8') as f:
        tpldata = json.loads(f.read())
        repeatKey = tpldata.get('repeatKey')
        data = tpldata.get('data')
        repeat_data = jsonpath.jsonpath(data, repeatKey)
        if repeat_data is not False:
            newItems = []
            for times in range(count):
                for item in repeat_data[0]:
                    newItems.append(item)
            set_val(data, repeatKey, newItems)
            set_val(params, 'http.post_argument_value', json.dumps(data, ensure_ascii=False))

    # 读取模板
    with open(jmx_path, encoding='utf-8') as f:
        tpl = f.read()
        jmx = jinja2.Template(tpl).render(params)
        with open(jmx_file, "w+", encoding="utf-8") as file:
            file.write(jmx)

    #执行jMeter
    jMeterUtil.run_cmd(JMETER_Home, jmx_file, result_file, report_html_dir)


if __name__ == '__main__':
    tpl_name = '凭证推送报文-需要登录'
    threads = [2, 5, 10]
    counts = [1, 25, 50, 100, 250, 500]
    for num_threads in threads:
        for count in counts:
            print(f'分录数{count * 2}, 线程数{num_threads}')
            run(tpl_name, num_threads, count)
